package com.zhouzj.task.springcloud.gateway.filter;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ip 防爆刷
 *
 * @Author: zhouzhijun
 * @Date: 2021/8/6 10:21
 */
@Slf4j
@Component
public class IpFilter implements GlobalFilter, Ordered {

    private static Map<String, List<Date>> ipCache = new HashMap<>();
    private static final Integer LIMIT_TIMES = 10;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();

        List<Date> enterTimes = ipCache.getOrDefault(clientIp, new ArrayList<>());
        enterTimes = enterTimes.stream()
                .filter(time -> time.after(DateUtil.date().offset(DateField.SECOND, -10)))
                .collect(Collectors.toList());
        enterTimes.add(DateUtil.date());
        ipCache.put(clientIp, enterTimes);

        if (enterTimes.size() > LIMIT_TIMES) {
            // 拒绝访问，状态码
            response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            String data = "Too Many Requests!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
